import { PageBase } from 'app/base';
import { XScrollableContainer } from './../../components/x-scrollable-container';
import { pagingMessage } from './../../components/y-scrollable-container';
import { NavigateService } from './../../services/navigate';
import { ExpeditionOrder } from './../../models/expeditionOrder';
import { ConfigSvr } from './../../services/config';
import { ActivatedRoute, Router } from '@angular/router';
import { ExpeditionOrderDishManage } from './../../components/expeditionOrderDishManage';
import { Orderitem, Order } from './../../models/order';
import { Observable } from 'rxjs/Observable';
import { Subscription, BehaviorSubject } from 'rxjs';
import { AppStore } from './../../services/appStore';
import { routeModel } from './../setup/index';
import { Component, OnInit, OnDestroy, ChangeDetectorRef, ViewChild, ElementRef } from '@angular/core';
import * as R from "ramda";

@Component({
    selector: 'new-finished-orders',
    styleUrls: ['./index.scss'],
    template: `
        <div class="pct-h100 new_finished_orders_container">
            <div class="inline_one_half pct-h100 left_box">
                <div class="title layout-row">
                    <div class="flex" [hidden]="(toggle$|async)">
                        已完成出品单 / {{currentOrders&&currentOrders.length || 0}}单
                    </div>
                    <div class="flex" [hidden]="!(toggle$|async)">
                        <input type="text" placeholder="请输入关键字" id="keyword" style="width: 95%;" />
                    </div>
                    <span id="toggle" style="display: flex;align-items: center;justify-content: center;"><i class="material-icons">search</i></span>
                </div>
                <div class="content">
                    <div class="center" *ngIf="!currentOrders || !currentOrders.length">没有订单</div>
                    <x-scrollable-container (change)="PagingMeaageChange($event)">
                        <div  item class="finished-order" *ngFor="let order of currentOrders;trackBy:trackById"  (click)="onViewDetails(order.id)" routerLinkActive="active">
                            <expedition-order-display [selected]="selectId==order.id" [expeditionOrder]="order">
                            </expedition-order-display>
                        </div>
                    </x-scrollable-container>
                </div>
                 <div class="bottom" *ngIf="pagingInfo&&pagingInfo.previousCount || pagingInfo&&pagingInfo.nextCount">
                    <page-btn [btnType]="'left-right'" [upNum]="pagingInfo&&pagingInfo.previousCount" [downNum]="pagingInfo&&pagingInfo.nextCount" (onUp)="up()" (onDown)="down()"></page-btn>
                </div>
            </div>
            <div class="inline_four pct-h100" style="float:right;">
                <deliver-orders [expeditionOrder]="order"></deliver-orders>
            </div>
        </div>
    `
})
export class NewFinishedOrders extends PageBase implements  OnDestroy {
    @ViewChild(XScrollableContainer)
    private xScrollableContainer: XScrollableContainer;

    private currentOrders: Array<ExpeditionOrder>;

    order: ExpeditionOrder
    isFinishPage = true;

    selectId: string
    onViewDetails(id) {
        this.navSvr.onViewDetails(id);
        // this.router.navigate(["../" + id], { relativeTo: this.route });
    }

    private up() {
        this.pagingInfo.turningPage(-1);
    }

    private down() {
        this.pagingInfo.turningPage(1);
    }

    pagingInfo: pagingMessage
    PagingMeaageChange(event) {
        this.pagingInfo = event;
    }

    constructor(private element: ElementRef, private changeDetectorRef: ChangeDetectorRef, private navSvr: NavigateService, private configSvr: ConfigSvr, private activeRouter: ActivatedRoute, private appStore: AppStore, private router: Router) {
        super()
    }

    getOrdersByKeyWord(orders, keyWord):Array<ExpeditionOrder>{
        return orders.filter(order=> order.serialNo.indexOf(keyWord)>-1 ||  order.items.some(item=>item.customerIdentity.indexOf(keyWord)>-1))
    }
    toggle$
    async ngAfterViewInit() {
        this.navSvr.registerRoute(this.activeRouter);
       

        const search$ = Observable.fromEvent(this.element.nativeElement.querySelector("#keyword"), 'input')  
        .map(e => (<any>e).target.value)
        .debounceTime(1000)
        .distinctUntilChanged().startWith("")
        const toggle$ = Observable.fromEvent(this.element.nativeElement.querySelector("#toggle"), 'click')
              .scan(R.not, false).startWith(false).distinctUntilChanged().do(data=>{
                  if(data) setTimeout(() => {
                      this.element.nativeElement.querySelector("#keyword").focus();
                  }, 10); 
              });  
        this.toggle$ = toggle$;
        const keyWord$ =  Observable.combineLatest(search$,this.toggle$).map(([search, toggle])=>{
            if(toggle) return search;
            else return "";
        }).distinctUntilChanged();


        const init$ = Observable.fromPromise(this.appStore.orderStore.getExpeditedExpeditionOrders()).do(orders=>{
            const firstOrder = orders && orders[0];
            const currentOrderId = firstOrder&&firstOrder.id;
            this.router.navigate(["newFinishedOrders/" + currentOrderId]);
            return orders;
        })
        const currentOrders$ = init$.combineLatest(keyWord$).map(([orders, keyWord])=>{
            if(!keyWord) return orders;
            else return this.getOrdersByKeyWord(orders, keyWord) 
        })
        this.subscribetions.push(currentOrders$.subscribe(orders=>{
            this.currentOrders = R.take(200,orders);
            this.changeDetectorRef.detectChanges();
            this.xScrollableContainer.childrenChanged();
        }));

        const paramsId$ = this.activeRouter.params.map(params => params["id"]);
        const order$ =  Observable.combineLatest(currentOrders$, paramsId$).map(([currentOrders, paramsId])=>{
             const order = this.currentOrders.find(x => x.id == paramsId);
             return order;
        })

        this.subscribetions.push(order$.subscribe(order=>{
            if (!order) {
                return;
            }
            this.selectId = order.id;
            this.order = order;
        }))
    }
}


